package cn.sc.hunter.day2.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 操作属性文件工具类
 */
public final class PropertiesUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);

    /**
     * 加载属性文件
     */
    public static Properties loadProperties(String fileName) {
        Properties properties = null;
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            if (is == null) {
                throw new FileNotFoundException(fileName + "文件找不到");
            }
            properties = new Properties();
            properties.load(is);
        } catch (IOException e){
            LOGGER.error("加载属性文件出错", e);
        } finally {
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("关闭 Input 流出错", e);
                }
            }
        }
        return properties;
    }

    /**
     * 获取字符型属性（默认空字符串）
     */
    public static String getString(Properties properties, String key){
        return getString(properties, key, "");
    }

    /**
     * 获取字符型属性（可指定默认值）
     */
    public static String getString(Properties properties, String key, String defaultValue){
        String value = defaultValue;
        if (properties.containsKey(key)){
            value = properties.getProperty(key);
        }
        return value;
    }

    /**
     * 获取数字型属性（默认值 0）
     */
    public static int getInt(Properties properties, String key){
        return getInt(properties, key, 0);
    }

    /**
     * 获取数字型属性（可指定默认值）
     */
    public static int getInt(Properties properties, String key, int defaultValue){
        int value = defaultValue;
        if (properties.containsKey(key)){
            value = CastUtil.castInt(properties.getProperty(key));
        }
        return value;
    }

    /**
     * 获取布尔型属性（默认值 false）
     */
    public static Boolean getBoolean(Properties properties, String key){
        return getBoolean(properties, key, false);
    }

    /**
     * 获取布尔型属性（可指定默认值）
     */
    public static Boolean getBoolean(Properties properties, String key, Boolean defaultValue){
        Boolean value = defaultValue;
        if (properties.containsKey(key)){
            value = CastUtil.castBoolean(properties.getProperty(key));
        }
        return value;
    }
}
